<template>
  <div>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-position="left" label-width="0px" class="login-form">
      <h3 class="title">
        注册
      </h3>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号名">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码" @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="repassword">
        <el-input v-model="loginForm.repassword" type="password" auto-complete="off" placeholder="再次输入密码" @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="lock" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="phone">
        <el-input v-model="loginForm.phone" type="text" auto-complete="off" placeholder="手机号码" @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="phone" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="nickname">
        <el-input v-model="loginForm.nickname" type="text" auto-complete="off" placeholder="名字 (显示)">
          <svg-icon slot="prefix" icon-class="edit" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="email">
        <el-input v-model="loginForm.email" type="text" auto-complete="off" placeholder="邮箱 (选填)" @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="email" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item label="性别 (选填)" label-width="100px">
        <el-radio-group v-model="loginForm.gender">
          <el-radio label="1">男</el-radio>
          <el-radio label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode">
        </div>
      </el-form-item>
      <!--      插槽位置-->
      <slot />
      <el-form-item style="width:100%;">
        <el-button :loading="loading" size="medium" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
          <span v-if="!loading">注 册</span>
          <span v-else>注 册 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div v-if="$store.state.settings.showFooter" id="el-login-footer">
      <span v-html="$store.state.settings.footerTxt" />
      <span> ⋅ </span>
      <a href="https://beian.miit.gov.cn/#/Integrated/index" target="_blank">{{ $store.state.settings.caseNumber }}</a>
    </div>
  </div>
</template>

<script>
import { encrypt } from '@/utils/rsaEncrypt'
import { getCodeImg } from '@/api/login'
import Cookies from 'js-cookie'
import qs from 'qs'
import Background from '@/assets/images/background.jpg'
import { validateEMAIL, validatePhone } from '@/utils/validate'
export default {
  name: 'Reg',
  data() {
    return {
      Background: Background,
      codeUrl: '',
      cookiePass: '',
      loginForm: {
        username: '',
        password: '',
        repassword: '',
        phone: '',
        email: '',
        nickname: '',
        gender: '1',
        code: '',
        uuid: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '账号名不能为空' }, { required: true, trigger: 'blur', validator: this.validateUSERNAME }],
        nickname: [{ required: true, trigger: 'blur', message: '名字不能为空' }],
        phone: [{ required: true, trigger: 'blur', message: '电话号码不能为空' }, { required: true, trigger: 'blur', validator: validatePhone }],
        password: [{ required: true, trigger: 'blur', message: '密码不能为空' }],
        repassword: [{ required: true, trigger: 'blur', message: '密码不一致', validator: this.validateConfirmPassword }],
        email: [{ required: false, trigger: 'blur', message: '邮箱格式不正确', validator: validateEMAIL }],
        code: [{ required: true, trigger: 'change', message: '验证码不能为空' }]
      },
      isRepName: false,
      loading: false,
      redirect: undefined
    }
  }, computed: {
    getGender() {
      if (this.gender === 1) return '男'
      else return '女'
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const data = route.query
        if (data && data.redirect) {
          this.redirect = data.redirect
          delete data.redirect
          if (JSON.stringify(data) !== '{}') {
            this.redirect = this.redirect + '&' + qs.stringify(data, { indices: false })
          }
        }
      },
      immediate: true
    }
  },
  created() {
    // 获取验证码
    this.getCode()
    // 获取用户名密码等Cookie
    this.getCookie()
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = res.img
        this.loginForm.uuid = res.uuid
      })
    },
    getCookie() {
      const username = Cookies.get('username')
      let password = Cookies.get('password')
      // 保存cookie里面的加密后的密码
      this.cookiePass = password === undefined ? '' : password
      password = password === undefined ? this.loginForm.password : password
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password,
        code: ''
      }
    },
    handleLogin() {
      if (this.isRepName) alert('请输入正确的表单')
      else {
        this.$refs.loginForm.validate(async valid => {
          await this.regUser()
          const user = {
            username: this.loginForm.username,
            nickname: this.loginForm.nickname,
            password: this.loginForm.password,
            code: this.loginForm.code,
            uuid: this.loginForm.uuid
          }
          if (user.password !== this.cookiePass) {
            user.password = encrypt(user.password)
          }
          if (valid) {
            this.loading = true
            this.$store.dispatch('Login', user).then(() => {
              this.loading = false
              this.$router.push({ path: this.redirect || '/' })
            }).catch(() => {
              this.loading = false
              this.getCode()
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    validateConfirmPassword(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入确认密码'))
      } else if (value !== this.loginForm.password) {
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    },
    async validateUSERNAME(rule, value, callback) {
      if (value === '' || value === undefined || value === null) {
        callback()
      } else {
        await this.isExistName()
        if (this.isRepName) {
          callback(new Error('用户名已存在'))
        } else {
          callback()
        }
      }
    },
    async isExistName() {
      var axios = require('axios')
      var data = ''

      var config = {
        method: 'get',
        url: 'http://localhost:8080/register?username=' + this.loginForm.username,
        headers: {},
        data: data
      }

      let statuscode = ''
      // eslint-disable-next-line vue/no-async-in-computed-properties
      await axios(config)
        .then(function(response) {
          statuscode = response.data.code
          console.log(statuscode)
        })
        .catch(function(error) {
          return error
        })
      // eslint-disable-next-line eqeqeq
      this.isRepName = statuscode == '0'
      console.log(this.isRepName)
    },
    regUser() {
      var axios = require('axios')
      var data = JSON.stringify({
        'username': this.loginForm.username,
        'nickname': this.loginForm.nickname,
        'password': this.loginForm.password,
        'email': this.loginForm.email,
        'phone': this.loginForm.phone,
        'gender': this.getGender
      })

      var config = {
        method: 'post',
        url: 'http://localhost:8080/register',
        headers: {
          'Content-Type': 'application/json'
        },
        data: data
      }

      axios(config)
        .then(function(response) {
          console.log(JSON.stringify(response.data))
        })
        .catch(function(error) {
          console.log(error)
        })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-size: cover;
  }
  .title {
    margin: 0 auto 30px auto;
    text-align: center;
    color: #707070;
  }

  .login-form {
    border-radius: 6px;
    background: #ffffff;
    width: 385px;
    padding: 25px 25px 5px 25px;
    .el-input {
      height: 38px;
      input {
        height: 38px;
      }
    }
    .input-icon{
      height: 39px;width: 14px;margin-left: 2px;
    }
  }
  .login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
  }
  .login-code {
    width: 33%;
    display: inline-block;
    height: 38px;
    float: right;
    img{
      cursor: pointer;
      vertical-align:middle
    }
  }
</style>
